var ctx="/workflow/";
var token = "";
var authorization = "";

//获取URL参数值
function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null)return unescape(r[2]);
    return null;
}

function saveToken(xhr){
    if(xhr){
        let newAuthorization = xhr.getResponseHeader("Authorization");
        if(newAuthorization != undefined && newAuthorization != "" && newAuthorization != authorization){
            authorization = newAuthorization;
            token = newAuthorization.substring(7);
            window.sessionStorage.setItem("token", token);
            window.sessionStorage.setItem("authorization", authorization);
        }
    }
}

if(token == ""){
    let newToken = getQueryString("token");
    if(newToken != undefined && newToken != "" && newToken != null && newToken != token){
        token = newToken;
        authorization = "Bearer " + newToken;
        window.sessionStorage.setItem("token", token);
        window.sessionStorage.setItem("authorization", authorization);
    }
    let sessionToken = window.sessionStorage.getItem("token");
    if(sessionToken != null && token == ""){
        token = sessionToken;
        authorization = window.sessionStorage.getItem("authorization");
    }
}

var api = {
    addUrl: function (url,obj){
        //如果省略url，则为post请求，令obj为url，令url为null
        if(arguments.length==1){
            obj=url;
            url=null;
        }
        //url不为空(get请求: 设置url信息)
        if(!!url){
            for(var k in obj){
                url += (url.indexOf("?")==-1 ? "?" : "&");
                url+=encodeURIComponent(k)+ "=" +encodeURIComponent(obj[k]);
            }
        }else{
            //post请求(设置data信息)
            url="";
            for(var k in obj){
                url+=encodeURIComponent(k)+ "=" +encodeURIComponent(obj[k]);
                url+="&";
            }
            //删除最后一个&
            var arr=url.split("");
            arr.pop();
            url=arr.join("");
        }
        //返回拼接好的信息
        return url;
    },
    get: function (url,data,fn,ojson){
        let xhr = new XMLHttpRequest();
        //省略data时,即不发送数据
        if(typeof data =="function"){
            ojson=fn;
            fn=data;
            data={};
        }
        //合并url和data信息
        url=this.addUrl(url,data)
        //是否异步发送
        xhr.open("get",url,true);
        xhr.setRequestHeader("Authorization", authorization);

        xhr.onreadystatechange = function () {
            if (this.readyState === 4) {
                if (this.status === 200) {
                    saveToken(xhr);

                    fn(JSON.parse(this.responseText));
                } else {
                    var resJson = { code: this.status, msg: this.response }
                    fn(resJson);
                }
            }
        };

        xhr.send(null);
    },
    post: function (url,data,fn,ojson){
        var xhr = new XMLHttpRequest();
        //省略data时,即不发送数据
        if(typeof data =="function"){
            ojson=fn;
            fn=data;
            data={};
        }
        //合并data信息
        data=this.addUrl(data);
        //是否异步发送
        xhr.open("post",url,true);
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhr.setRequestHeader("Authorization", authorization);

        xhr.onreadystatechange = function () {
            if (this.readyState === 4) {
                if (this.status === 200) {
                    saveToken(xhr);

                    fn(JSON.parse(this.responseText));
                } else {
                    var resJson = { code: this.status, msg: this.response }
                    fn(resJson);
                }
            }
        };

        xhr.send(data);
    },

    postJson: function (url,data,fn,ojson){
        let xhr = new XMLHttpRequest();
        xhr.open("POST", url, true);
        xhr.setRequestHeader("Content-type", "application/json;charset=utf-8");
        xhr.setRequestHeader("Authorization", authorization);

        xhr.onreadystatechange = function () {
            if (this.readyState === 4) {
                if (this.status === 200) {
                    saveToken(xhr);

                    fn(JSON.parse(this.responseText));
                } else {
                    var resJson = { code: this.status, msg: this.response }
                    fn(resJson);
                }
            }
        };

        xhr.send(JSON.stringify(data));
    },

    getSync: function (url,data,fn){
        let xhr = new XMLHttpRequest();
        //省略data时,即不发送数据
        if(typeof data =="function"){
            fn=data;
            data={};
        }
        //合并url和data信息
        url=this.addUrl(url,data)
        //是否异步发送
        xhr.open("get",url,false);
        xhr.setRequestHeader("Authorization", authorization);

        xhr.onreadystatechange = function () {
            if (this.readyState === 4) {
                if (this.status === 200) {
                    saveToken(xhr);

                    fn(JSON.parse(this.responseText));
                } else {
                    var resJson = { code: this.status, msg: this.response }
                    fn(resJson);
                }
            }
        };

        xhr.send(null);
    },

    postJsonSync: function (url,data,fn){
        let xhr = new XMLHttpRequest();
        xhr.open("POST", url, false);
        xhr.setRequestHeader("Content-type", "application/json;charset=utf-8");
        xhr.setRequestHeader("Authorization", authorization);

        xhr.onreadystatechange = function () {
            if (this.readyState === 4) {
                if (this.status === 200) {
                    saveToken(xhr);

                    fn(JSON.parse(this.responseText));
                } else {
                    var resJson = { code: this.status, msg: this.response }
                    fn(resJson);
                }
            }
        };

        xhr.send(JSON.stringify(data));
    },

    /*postJsonPromise: function (url,data,fn){
        new Promise( (resolve, reject) => {
            var xhr = new XMLHttpRequest()
            xhr.open("POST", url, true)
            xhr.setRequestHeader("Content-type", "application/json;charset=utf-8");

            xhr.onreadystatechange = function () {
                if (this.readyState === 4) {
                    if (this.status === 200) {
                        resolve(JSON.parse(this.responseText), this)
                    } else {
                        var resJson = { code: this.status, response: this.response }
                        reject(resJson, this)
                    }
                }
            };

            xhr.send(JSON.stringify(data));
        }).then( res => {
            fn(res);
        });
    },*/

    // 下载
    download: function (url,data,fn){
    	let xhh = new XMLHttpRequest();
    	xhh.open("post", url);
    	xhh.setRequestHeader("Content-Type", "application/json;charset=utf-8");
        xhh.setRequestHeader("Authorization", authorization);

    	xhh.responseType = 'blob';
        xhh.onreadystatechange = function () {
            if (xhh.readyState === 4 && xhh.status === 200) {
                saveToken(xhh);

                var name = xhh.getResponseHeader("Content-disposition");
                //var filename = name.substring(20,name.length);
                if(name){
                    filename = name.includes('filename=') ? decodeURIComponent(name.split("=")[1]) : "下载的文件";
                } else {
                    let u1 = url.substring(url.lastIndexOf('/')+1);
                    if(u1.indexOf('?') > -1){
                        filename = u1.substring(0, u1.indexOf('?'));
                    } else {
                        filename = u1;
                    }
                }
                var blob = new Blob([xhh.response], {type: xhh.response.type});
                var csvUrl = URL.createObjectURL(blob);
                var link = document.createElement('a');
                link.href = csvUrl;
                link.download = filename;
                link.click();

                if(typeof fn =="function"){
                    fn();
                }
         }
       };
       xhh.send(JSON.stringify(data));
    },

    // 下载
    downloadGet: function (url,data,fn){
        let xhh = new XMLHttpRequest();
        //省略data时,即不发送数据
        if(typeof data =="function"){
            ojson=fn;
            fn=data;
            data={};
        }
        //合并url和data信息
        url=this.addUrl(url,data)
        xhh.open("get", url,true);
        xhh.setRequestHeader("Authorization", authorization);

        xhh.responseType = 'blob';
        xhh.onreadystatechange = function () {
            if (xhh.readyState === 4 && xhh.status === 200) {
                saveToken(xhh);

                let name = xhh.getResponseHeader("Content-disposition");
                let filename = "下载的文件";
                if(name){
                    filename = name.includes('filename=') ? decodeURIComponent(name.split("=")[1]) : "下载的文件";
                } else {
                    let u1 = url.substring(url.lastIndexOf('/')+1);
                    if(u1.indexOf('?') > -1){
                        filename = u1.substring(0, u1.indexOf('?'));
                    } else {
                        filename = u1;
                    }
                }
                //let filename = name.substring(20,name.length);
                let blob = new Blob([xhh.response], {type: xhh.response.type});
                let csvUrl = URL.createObjectURL(blob);
                let link = document.createElement('a');
                link.href = csvUrl;
                link.download = filename;
                link.click();

                if(typeof fn =="function"){
                    fn();
                }
            }
        };
        xhh.send(null);
    },

    //字符串转换json
    json: function (str){
        return (new Function("return " + str))();
    },
    success: function (fn,ojson){
        //当请求完成之后调用回调函数返回数据
        var self=this;
        this.xhr.onreadystatechange=function (){
            var odata;
            if(self.xhr.readyState == 4){
                if((self.xhr.status>=200 && self.xhr.status<300) || self.xhr.status == 304){
                    odata=self.xhr.responseText;
                    //若为json则转化json格式
                    if(ojson==="json"){
                        odata=self.json(odata);
                    }
                    fn(odata);
                }else{
                    odata="request was unsuccessful: "+self.xhr.status;
                    fn(odata);
                }
            }
        }
    },
    //取消异步请求
    cancel: function (){
        this.xhr.abort();
        return this;
    }


}
